from fastapi import FastAPI
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
from langchain_community.llms import Tongyi
from langserve import add_routes
import os
from dotenv import find_dotenv,load_dotenv

env = load_dotenv(find_dotenv())

os.environ["DASHSCOPE_API_KEY"] = os.getenv('ALI_API_KEY')

# 1. 创建提示词模版
system_template = "Translate the following into {language}:"
prompt_template = ChatPromptTemplate.from_messages([
    ('system', system_template),
    ('user', '{text}')
])

# 2. 创建模型
model = Tongyi()

# 3. 创建解析器
parser = StrOutputParser()

# 4. 创建链
chain = prompt_template | model | parser

# 5. App 定义
app = FastAPI(
    title="LangChain Server",
    version="1.0",
    description="使用 LangChain 的 Runnable 接口的简单 API 服务器",
)

# 6. 添加链路由
add_routes(
    app,
    chain,
    path="/chain",
)

if __name__ == "__main__":
    import uvicorn

    uvicorn.run(app, host="127.0.0.1", port=5100)
